package my.jwds.p355;

public class IsSelfCrossing {

    public static void main(String[] args) {
        IsSelfCrossing obj = new IsSelfCrossing();

        System.out.println(obj.isSelfCrossing(new int[]{1,1,2,1}));
    }

    public boolean isSelfCrossing(int[] distance) {
        int x = 0;
        int y = 0;
        int[][][]  segments = new int[4][][];
        for (int i = 0; i < segments.length; i++) {
            segments[i] = new int[2][4];
            segments[i][0] = new int[4];
            segments[i][1] = new int[4];
        }
        for (int i = 0; i < distance.length; i++) {
            int [][] segment = segments[i%4];
            int []prev = segment[0];
            int []now = segment[1];
            copyValue(now,prev);
            switch (i%4){
                case 0:
                    now[0] = x;
                    now[1] = y;
                    y+=distance[i];
                    now[2] = x;
                    now[3] = y;
                    break;
                case 1:
                    now[2] = x;
                    now[3] = y;
                    x-=distance[i];
                    now[0] = x;
                    now[1] = y;
                    break;
                case 2:
                    now[2] = x;
                    now[3] = y;
                    y-=distance[i];
                    now[0] = x;
                    now[1] = y;
                    break;
                case 3:
                    now[0] = x;
                    now[1] = y;
                    x+=distance[i];
                    now[2] = x;
                    now[3] = y;
                    break;
            }
            if (i>=3 && (searchIntersect(segments[(i%4+1)%4][1],now,i%2)||searchIntersect(segments[(i%4+3)%4][0],now,i%2)))return true;
        }
        return false;
    }


    public boolean searchIntersect(int[] segment,int[] search,int type){
        if (type == 1){
            int [] temp = search;
            search = segment;
            segment = temp;
        }
        return segment[0] <= search[0] && segment[2]>= search[0] && search[1] <= segment[1] && search[3] >= segment[1];
    }


    public void copyValue(int [] origin,int[] copyTo){
        for (int i = 0; i < origin.length; i++) {
            copyTo[i] = origin[i];
        }
    }
}